<template>
  <Dialog
    v-model="dialogVisible"
    :appendToBody="true"
    :top="'5vh'"
    :title="dialogTitle"
    width="70%"
  >
    <ContentWrap>
      <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="68px">
        <el-form-item label="展示方式" prop="showType">
          <el-select
            v-model="queryParams.showType"
            clearable
            disabled
            @change="handleShowTypeChange"
            class="!w-240px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SHOW_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型" prop="spuType" v-if="queryParams.showType == 1">
          <el-select v-model="queryParams.spuType" clearable class="!w-240px">
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SPU_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              :disabled="dict.value == 7"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品名称" prop="spuName">
          <el-input
            v-model="queryParams.spuName"
            class="!w-240px"
            clearable
            placeholder="请输入商品名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="商品分类" v-if="queryParams.showType == 0" prop="categoryId">
          <el-cascader
            v-model="queryParams.categoryId"
            :options="categoryList"
            :props="defaultProps"
            class="!w-240px"
            clearable
            filterable
            placeholder="请选择商品分类"
          />
        </el-form-item> -->
        <!-- <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-240px"
            end-placeholder="结束日期"
            start-placeholder="开始日期"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <!-- SPU列表 -->
      <el-table
        ref="spuListRef"
        v-loading="loading"
        :data="list"
        row-key="spuId"
        v-if="queryParams.showType == 0"
        @expand-change="expandChange"
      >
        <!-- <el-table-column v-if="isSelectSku" type="expand" width="30">
          <template #default="{ row }">
            <SkuList
              v-if="row.isExpand"
              ref="skuListRef"
              :isComponent="true"
              :prop-form-data="row.spuData"
              :property-list="row.propertyList"
              @selection-change="selectSku"
            />
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="" width="45">
          <template #header>
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            />
          </template>
          <template #default="{ row }">
            <el-checkbox
              v-model="row.allCheck"
              :indeterminate="row.isIndeterminate"
              @change="handleCheckedAllItemChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column key="spuId" align="center" label="ID" prop="spuId" />

        <el-table-column
          :show-overflow-tooltip="true"
          align="left"
          label="商品信息"
          min-width="300"
          prop="spuName"
        >
          <template #default="{ row }">
            <div class="flex items-center">
              <el-image
                :src="row.picUrl"
                class="h-30px w-30px mr-10px"
                @click="imagePreview(row.picUrl)"
              />
              <!-- 卡类商品 -->
              <div class="flex items-center" v-if="row.spuType == 4">
                <el-text truncated> {{ row.spuName }} </el-text>
              </div>
              <!-- 代金券 -->
              <div class="flex items-center" v-else-if="row.spuType == 7">
                <el-tag class="mr-5px!"> 领取方式</el-tag>
                <el-text truncated> {{ row.spuName }} </el-text>
              </div>
              <!-- 商品 -->
              <div class="flex items-center" v-else>
                <!-- <el-tag class="mr-5px!" v-if="row.brandName"> {{ row.brandName }}</el-tag> -->
                <el-text truncated> {{ row.spuName }} </el-text>
              </div>
            </div>
          </template></el-table-column
        >
        <el-table-column align="center" label="属性" min-width="90" prop="spuPropertyName" />

        <el-table-column
          align="center"
          label="规格"
          :show-overflow-tooltip="true"
          min-width="90"
          prop="specType"
        />
        <el-table-column align="center" label="零售价" min-width="150" prop="priceRange" />
        <el-table-column align="center" label="最低价" min-width="90" prop="price" />
        <el-table-column align="center" label="销量" min-width="90" prop="salesCount" />
        <el-table-column align="center" label="销售渠道" min-width="90" prop="salesChannelName" />
        <el-table-column align="center" label="状态" min-width="90" prop="status" />
      </el-table>
      <!-- SKU列表 -->
      <SkuList
        v-if="queryParams.showType == 1"
        ref="skuListRef"
        :isComponent="true"
        :isDetail="true"
        :prop-form-data="spuData"
        @select-row="selectRowSku"
      />

      <!-- 分页 -->
      <Pagination
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNo"
        :total="total"
        @pagination="handleQuery"
      />
    </ContentWrap>
    <template #footer>
      <el-button type="primary" @click="confirm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ElTable } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import SkuList from './SkuList.vue'
// import * as ProductCategoryApi from '@/api/mall/product/category'
import * as ProductSpuApi from '@/api/shop/product/spu'

import { propTypes } from '@/utils/propTypes'
import { floatToFixed2, formatToFraction } from '@/utils'

defineOptions({ name: 'PromotionSpuSelect' })

const props = defineProps({
  // 默认不需要（不需要的情况下只返回 spu，需要的情况下返回 选中的 spu 和 sku 列表）
  // 其它活动需要选择商品和商品属性导入此组件即可，需添加组件属性 :isSelectSku='true'
  isSelectSku: propTypes.bool.def(false), // 是否需要选择 sku 属性
  radio: propTypes.bool.def(false) // 是否单选 sku
})
const selection = {
  label: '', // 如果需要表格多选，此处label必须设置
  minWidth: 55,
  fixed: 'left',
  slot: 'selection',
  headerSlot: 'selectionHeader'
}
const message = useMessage() // 消息弹窗
const total = ref(0) // 列表的总页数
const list = ref<any[]>([]) // 列表的数据
const loading = ref(false) // 列表的加载中
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  tabType: 0,
  spuName: '',
  // categoryId: undefined,
  createTime: undefined,
  showType: 1, //商品展示方式 0 SPU 1 SKU
  skuType: [], //商品属性
  spuType: ''
}) // 查询参数
const spuListRef = ref<InstanceType<typeof ElTable>>()
const skuListRef = ref<InstanceType<typeof SkuList>>() // 商品属性选择 Ref

const checkAll = ref(false)
// const isIndeterminate = ref(false)
//============ 商品选择相关 ============
const selectedSpuIds = ref<number[]>([]) // 选中的商品 spuId
const selectedSkuIds = ref<any[]>([]) // 选中的商品 skuIds
const echoSelectedSkuIds = ref<any[]>([]) //回显选中 (现在直接操作这个数据 用来处理二次编辑的回显)
const selectRowSku = (params) => {
  if (params.type == 'add') {
    echoSelectedSkuIds.value.push(params.skuId)
  } else {
    echoSelectedSkuIds.value = echoSelectedSkuIds.value.filter((ele) => {
      return ele != params.skuId
    })
  }
}
// const selectSku = (val: ProductSpuApi.Sku[], spuData?) => {
//   // 如果是SPU列表
//   if (queryParams.value.showType == 0) {
//     if (val.length === 0) {
//       selectedSkuIds.value[spuData.spuId] = []
//       return
//     } else {
//       selectedSkuIds.value[spuData.spuId] = val
//     }
//     const nowSpu = list.value.find((ele) => {
//       return ele.spuId == spuData.spuId
//     })
//     nowSpu.allCheck = spuData.spuIsAllCheck
//     nowSpu.isIndeterminate = spuData.spuIsIndeterminate
//     updateCheckedStatus()
//   }
//   // 如果是SKU列表
//   if (queryParams.value.showType == 1) {
//     if (val.length === 0) {
//       selectedSkuIds.value = []
//       return
//     } else {
//       selectedSkuIds.value = val.map((sku) => sku.skuId!)
//     }
//   }
// }
const handleCheckAllChange = (val: boolean) => {
  // 点击最外层的全选
  list.value.forEach((ele: any) => {
    ele.allCheck = val
    ele.isIndeterminate = false
    handleCheckedAllItemChange(ele)
  })
  selectedSpuIds.value = val
    ? list.value.map((ele) => {
        return ele.spuId
      })
    : []
} //全选
const handleCheckedAllItemChange = (row: any) => {
  row.isIndeterminate = false

  if (row.spuData) {
    if (row.allCheck) {
      row.spuData.skus.forEach((ele) => {
        ;(ele.isCheck = true), (ele.isIndeterminate = false)
      })
    } else {
      row.spuData.skus.forEach((ele) => {
        ;(ele.isCheck = false), (ele.isIndeterminate = false)
      })
    }
  }
  updateCheckedStatus()
}
const updateCheckedStatus = () => {
  selectedSpuIds.value = list.value
    .filter((ele) => {
      return ele.allCheck || (!ele.allCheck && ele.isIndeterminate)
    })
    .map((ele) => {
      return ele.spuId
    })
  const checkedCount = selectedSpuIds.value.length
  checkAll.value = checkedCount === list.value.length
} //更新最外层的选中状态
const isIndeterminate = computed(() => {
  // 没有全部选中但子级又有值
  let isNoCheckAll = list.value.filter((ele) => {
    return !ele.allCheck && !ele.isIndeterminate
  })
  let isChildrenNoCheckAll = list.value.filter((ele) => {
    return !ele.allCheck && ele.isIndeterminate
  })

  let status = false
  if (checkAll.value) {
    if (isChildrenNoCheckAll.length > 0) {
      status = true
    }
    // 如果是全选
  } else {
    // 如果不是权限
    if (isNoCheckAll.length > 0 && isNoCheckAll.length < list.value.length) {
      status = true
    }
  }

  return status
})

// 计算商品属性
const expandChange = async (row: ProductSpuApi.Spu) => {
  if (row.isExpand && row.spuData === row.spuId) {
    return
  }
  row.spuData = {}
  row.propertyList = []
  row.isExpand = false
  // if (expandedRows?.length === 0) {
  //   // 如果展开个数为 0
  //   expandRowKeys.value = []
  //   return
  // }
  // 获取 SPU 详情
  const res = (await ProductSpuApi.getSkuPageList({
    spuId: row.spuId,
    spuType: row.spuType
  })) as ProductSpuApi.Spu
  // row.propertyList = getPropertyList(res)

  row.propertyList = res.propertyList
  row.propertyList.unshift(selection)
  row.spuData.skus = res.list
  // expandRowKeys.value = [row.spuId!]
  if (row.allCheck) {
    row.spuData.skus!.forEach((element) => {
      element.isCheck = true
    })
  } else if (!row.allCheck && row.isIndeterminate) {
    row.spuData.skus!.forEach((element) => {
      if (selectedSkuIds.value[row.spuId!].includes(element.skuId)) {
        element.isCheck = true
      }
    })
  }
  row.isExpand = true
}

// 确认选择时的触发事件
const emits = defineEmits<{
  (e: 'confirm', spuId: number[], skuIds?: number[]): void
}>()
/**
 * 确认选择返回选中的 spu 和 sku (如果需要选择sku的话)
 */
const confirm = () => {
  if (echoSelectedSkuIds.value.length === 0) {
    message.warning('没有选择任何商品')
    return
  }

  emits('confirm', echoSelectedSkuIds.value)
  // 关闭弹窗
  dialogVisible.value = false
  if (queryParams.value.showType == 1) {
    skuListRef.value.getSkuTableRef()?.clearSelection()
  }
  // selectedSpuIds.value = []
  // selectedSkuIds.value = []
}

/** 打开弹窗 */
const open = (selecteds?) => {
  if (queryParams.value.showType == 1) {
    echoSelectedSkuIds.value = selecteds || []
  }
  dialogTitle.value = '商品选择'
  dialogVisible.value = true
  resetQuery()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // const data = await ProductSpuApi.getSpuPageList(queryParams.value)
    // list.value = data.list
    // total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 查询sku列表 */
const spuData = ref({
  skus: []
}) //为了统一组件格式
const getSkuPageList = async () => {
  loading.value = true
  try {
    const data = await ProductSpuApi.getSkuPageList2(queryParams.value)
    data.list?.forEach((item) => {
      item.price = floatToFixed2(item.price)
      item.lowPrice = floatToFixed2(item.lowPrice)
    })
    spuData.value.skus = data.list
    total.value = data.total
    const selectedSkusRow = data.list.filter((ele) => {
      return echoSelectedSkuIds.value.includes(ele.skuId)
    })
    nextTick(() => {
      selectedSkusRow.forEach((ele) => {
        ele.isSelect = true
        skuListRef?.value?.getSkuTableRef()?.toggleRowSelection(ele, true)
      })
    })
  } finally {
    loading.value = false
  }
}
const handleShowTypeChange = () => {
  handleQuery()
}
/** 搜索按钮操作 */
const handleQuery = () => {
  if (queryParams.value.showType == 0) {
    getList()
  }
  if (queryParams.value.showType == 1) {
    getSkuPageList()
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    tabType: 0, // 默认获取上架的商品
    spuName: '',
    showType: queryParams.value.showType,
    skuType: [], //商品属性
    spuType: '',
    // categoryId: null,
    createTime: undefined
  }
  handleQuery()
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    zIndex: 99999999,
    urlList: [imgUrl]
  })
}

// const categoryList = ref() // 分类树

/** 初始化 **/
onMounted(async () => {
  // await getList()
  // 获得分类树
  // const data = await ProductCategoryApi.getCategoryList({})
  // categoryList.value = handleTree(data, 'id', 'parentId')
})
</script>
